<?php

namespace App\Http\Requests;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;

/**
 * 登录
 *
 * @Desc:验证请求类
 *
 * @author: zhx
 *
 * @Time: 2023/8/10 10:37
 */
class LoginRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * 获取应用于请求的验证规则。
     *
     * @return array<string, \Illuminate\Contracts\Validation\Rule|array|string>
     */
    public function rules(): array
    {
        $config = config('amis.login');
        $r = [
            'username' => 'required|max:50',
            'password' => 'required|max:50',
        ];
        //如果需要验证码
        if ($config['captcha'] == 1) {
            $r['captcha'] = 'required|captcha';
        }
        if ($config['captcha'] == 2) {
            $r['box_code'] = 'required';
        }

        return $r;
    }

    public function messages(): array
    {
        $config = config('amis.login');
        $m = [
            'username.required' => '账号是必填字段。',
            'password.required' => '密码是必填字段。',
        ];
        //如果需要验证码
        if ($config['captcha'] == 1) {
            $m['captcha.required'] = '验证码是必填字段。';
            $m['captcha.captcha'] = '验证码填写错误。';
        }
        if ($config['captcha'] == 2) {
            $m['box_code.required'] = '请验证验证码。';
        }

        return $m;
    }

    public function all($keys = null)
    {
        $data = parent::all($keys);

        return $data;
    }

    protected function failedValidation(Validator $validator)
    {
        $error = $validator->errors()->all();
        throw new HttpResponseException(response()->json(['msg' => $error[0], 'code' => '500', 'data' => $error[0]], 500));
    }
}
